<template>
  <div class="app-container">
    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入网站名称或域名进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加静态网站')"
      >添加静态网站
      </el-button>
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="80" prop="id" label="ID" sortable="custom" />

      <el-table-column align="center" label="网站名称" prop="site_name">
        <template slot-scope="scope">
          <el-link :href="'https://' + scope.row.root_domain" target="_blank" type="primary">
            {{ scope.row.site_name }}
          </el-link>
        </template>
      </el-table-column>

      <el-table-column align="center" label="根域名" prop="root_domain">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.root_domain }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="关键词">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.keywords" placement="top">
            <span>{{ scope.row.keywords | truncate(30) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '激活' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="代码风格" width="120">
        <template slot-scope="scope">
          <el-tag :type="getCodeStyleType(scope.row.code_style)">
            {{ getCodeStyleLabel(scope.row.code_style) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="create_at" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.create_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="550">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleManageTemplates(scope.row)">模板管理</el-button>
          <el-button size="mini" type="primary" @click="handleManageMenus(scope.row)">菜单管理</el-button>
          <el-button size="mini" type="success" @click="handleManageCategories(scope.row)">分类管理</el-button>
          <el-button size="mini" type="info" @click="handleManagePages(scope.row)">页面管理</el-button>
          <el-button size="mini" type="danger" @click="handleAction('edit', scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      class="mt-dialog"
      :title="title"
      :width="width"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="100px">
        <el-form-item v-if="action !== 'delete'" label="网站名称">
          <el-input v-model="temp.site_name" placeholder="请输入网站名称" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="根域名">
          <el-input v-model="temp.root_domain" placeholder="例如：example.com" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="网站关键词">
          <el-input v-model="temp.keywords" type="textarea" :rows="3" placeholder="请输入网站关键词，用逗号分隔" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="系统提示词">
          <el-input v-model="temp.system_prompt" type="textarea" :rows="4" placeholder="请输入系统提示词" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="代码风格">
          <el-select v-model="temp.code_style" placeholder="请选择代码风格">
            <el-option
              v-for="item in codeStyleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            选择的代码风格将用于生成菜单、页脚等动态组件的HTML代码
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="模板管理">
          <div style="color: #909399; font-size: 14px; line-height: 1.5;">
            <p>现在支持多种类型的HTML模板管理：</p>
            <ul style="margin: 10px 0; padding-left: 20px;">
              <li>落地页模板</li>
              <li>产品页面模板</li>
              <li>通用页面模板</li>
              <li>布局模板</li>
              <li>组件模板</li>
            </ul>
            <p>请在保存后，点击"模板管理"按钮来添加和管理模板。</p>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="状态">
          <el-switch v-model="temp.is_active" active-text="激活" inactive-text="停用" />
        </el-form-item>

        <div v-if="action === 'delete'" style="text-align: center; font-size: 16px;">
          确认要删除网站 <strong>{{ temp.site_name }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除网站将同时删除所有相关的分类和页面数据！" type="warning" show-icon />
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getStaticSiteList,
  createStaticSite,
  updateStaticSite,
  deleteStaticSite
} from '@/api/spider/static_site'

export default {
  name: 'StaticSiteIndex',
  filters: {
    truncate(value, length = 50) {
      if (!value) return ''
      if (value.length <= length) return value
      return value.slice(0, length) + '...'
    }
  },
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        site_name: '',
        root_domain: '',
        keywords: '',
        system_prompt: '',
        code_style: 'bootstrap5',
        is_active: true
      },
      width: '60%',

      // 代码风格选项
      codeStyleOptions: [
        { value: 'bootstrap5', label: 'Bootstrap 5' },
        { value: 'bootstrap4', label: 'Bootstrap 4' },
        { value: 'tailwind', label: 'Tailwind CSS' },
        { value: 'bulma', label: 'Bulma' },
        { value: 'materialize', label: 'Materialize CSS' },
        { value: 'custom', label: '自定义' }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        site_name: '',
        root_domain: '',
        keywords: '',
        system_prompt: '',
        code_style: 'bootstrap5',
        is_active: true
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.listQuery.page,
        pageSize: this.listQuery.pageSize
      }
      if (this.kwInput) {
        params.search = this.kwInput
      }

      getStaticSiteList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.data = response.data.data
            this.total = response.data.total
          } else {
            this.$message.error('获取数据失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取数据失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '60%'
          this.title = '添加静态网站'
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'edit':
          this.width = '60%'
          this.title = '编辑静态网站'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
        case 'delete':
          this.width = '40%'
          this.title = '删除确认'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          createStaticSite(_data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateStaticSite(_data.id, _data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteStaticSite(_data.id).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSort(v) {
      // 排序功能暂不实现
      console.log('排序:', v)
    },
    handleManageTemplates(row) {
      this.$router.push({
        path: '/static-site/html-template/',
        query: { site_id: row.id, site_name: row.site_name }
      })
    },
    handleManageMenus(row) {
      this.$router.push({
        path: '/static-site/static-site-menu/',
        query: { site_id: row.id, site_name: row.site_name }
      })
    },
    handleManageCategories(row) {
      this.$router.push({
        path: '/static-site/static-site-category/',
        query: { site_id: row.id, site_name: row.site_name }
      })
    },
    handleManagePages(row) {
      this.$router.push({
        path: '/static-site/static-site-page/',
        query: { site_id: row.id, site_name: row.site_name }
      })
    },
    getCodeStyleLabel(style) {
      const option = this.codeStyleOptions.find(item => item.value === style)
      return option ? option.label : style || 'Bootstrap 5'
    },
    getCodeStyleType(style) {
      const types = {
        'bootstrap5': 'primary',
        'bootstrap4': 'success',
        'tailwind': 'info',
        'bulma': 'warning',
        'materialize': 'danger',
        'custom': ''
      }
      return types[style] || ''
    }
  }
}
</script>

<style scoped>
.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}
</style>
